require 'net/http'
require 'cgi'

class SourceController < ApplicationController

  def create
    Net::HTTP.start(SABAL_DOMAIN, SABAL_PORT) do |http|
      nonce = sprintf("%016x", rand(16 ** 16))
      created = Time.now.utc.xmlschema
      digested_key = SHA1.sha1(nonce + created + session[:key] + APP_KEY).to_s
      req = Net::HTTP::Post.new("/pages.xml")
      req.basic_auth CGI.escape(session[:id]), CGI.escape(APP_ID.to_s + ',' + nonce + ',' + created + ',' + digested_key)
      req.body = "<page><name>New</name><content>New</content></page>"
      response = http.request(req)
      puts response.body
      @name = Hash.from_xml(response.body)['page']['id']
    end
    redirect_to :action => 'edit', :name => @name
  end
  
  def edit
    @name = params[:name]
    session[:id] = params[:id] unless session[:id]
    session[:key] = params[:key] unless session[:key]
    @name = '0' unless @name # 0 is front page.
    Net::HTTP.start(SABAL_DOMAIN, SABAL_PORT) do |http|
      nonce = sprintf("%016x", rand(16 ** 16))
      created = Time.now.utc.xmlschema
      digested_key = SHA1.sha1(nonce + created + session[:key] + APP_KEY).to_s
      req = Net::HTTP::Get.new("/pages/#{@name}.xml")
      req.basic_auth CGI.escape(session[:id]), CGI.escape(APP_ID.to_s + ',' + nonce + ',' + created + ',' + digested_key)
      response = http.request(req)
      p response.body
      @content = Hash.from_xml(response.body)['page']['content']
    end
  end

  def commit
    @name = params[:name]
    @name = 'FrontPage' unless @name
    Net::HTTP.start(SABAL_DOMAIN, SABAL_PORT) do |http|
      nonce = sprintf("%016x", rand(16 ** 16))
      created = Time.now.utc.xmlschema
      digested_key = SHA1.sha1(nonce + created + session[:key] + APP_KEY).to_s
      req = Net::HTTP::Put.new("/pages/#{@name}.xml")
      req.basic_auth CGI.escape(session[:id]), CGI.escape(APP_ID.to_s + ',' + nonce + ',' + created + ',' + digested_key)
      req.body = "<page><content>#{CGI.escapeHTML params[:content]}</content></page>"
      response = http.request(req)
      @content = Hash.from_xml(response.body)['page']['content']
    end
    redirect_to :action => 'edit', :name => @name
  end
end
